﻿using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Nvigorate.Test.Comparer
{
    public class DataTableEqualityComparer : IEqualityComparer<DataTable>
    {
        private readonly DataRowEqualityComparer _rowComparer = new DataRowEqualityComparer();

        public bool Equals(DataTable x, DataTable y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (x == null || y == null) return false;
            if (!x.TableName.Equals(y.TableName)) return false;
            if (x.Rows.Count != y.Rows.Count) return false;

            foreach (DataRow row in x.Rows)
            {
                if (!y.Rows.Cast<DataRow>().Contains(row, _rowComparer)) return false;
            }

            return true;
        }

        public int GetHashCode(DataTable obj)
        {
            if (obj == null) return 0;
            int hash = obj.TableName.GetHashCode();

            foreach (var row in obj.Rows)
            {
                hash += row == null ? 0 : 29*row.GetHashCode();
            }

            return hash;
        }
    }

    public class DataRowEqualityComparer : IEqualityComparer<DataRow>
    {
        public bool Equals(DataRow x, DataRow y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (x == null || y == null) return false;

            return x.ItemArray.SequenceEqual(y.ItemArray);
        }

        public int GetHashCode(DataRow obj)
        {
            if (obj == null) return 0;
            int hashCode = 0;
            foreach (var item in obj.ItemArray)
            {
                hashCode += item == null ? 0 : 29*item.GetHashCode();
            }

            return hashCode;
        }
    }
}